<template>
    <div class="product-list">
        <!--搜索表单-->
        <div class="common-form">发货单信息</div>

        <el-form :model="orderFrom" disabled label-width="150px" class="demo-form-inline">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="发货单号">
                        <el-input v-model="orderFrom.deliveryNo" placeholder="请输入发货单号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">

                    <el-form-item label="发货日期">
                        <el-date-picker style="width: 100%;" v-model="orderFrom.deliveryTime" type="datetime"
                            placeholder="选择发货日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="发货方式">
                        <el-select clearable placeholder="请选择发货方式" @change="onFilterChnage"
                            v-model="orderFrom.deliveryType">
                            <el-option v-for="(item, index) in deliveryTypeList" :key="index" :label="item.name"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="发货人">
                        <el-input v-model="orderFrom.deliveryName" placeholder="请输入发货人" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户名称">
                        <el-input :value="orderFrom.order && orderFrom.order.extractName" placeholder="请输入客户"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="销售订单号">
                        <el-input v-model="orderFrom.orderNo" placeholder="请输入销售订单号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="订单总金额">
                        <el-input style="width: 100%;" :value="orderFrom.order && orderFrom.order.orderPrice"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="优惠总金额">
                        <el-input style="width: 100%;" :value="orderFrom.order && orderFrom.order.couponMoney"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="实际付款金额">
                        <el-input style="width: 100%;" :value="orderFrom.order && orderFrom.order.realPayPrice"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="订金满百补位金额">
                        <el-input style="width: 100%;" :value="orderFrom.order && orderFrom.order.depositOutAmount"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="orderFrom.status">
                    <!-- AUDITING("审核中", 10),
                        UNPAYMENT("待付款", 20),
                        PAY_AUDIT("付款审批", 30),
                        WAIT_TAKE("待提货", 40),
                        ALREADY_TAKE("已提货", 50),
                        AUDIT_REFUSE("审批拒绝",60), -->
                    <el-form-item label="审核状态">
                        <el-select placeholder="请选择审核状态" v-model="orderFrom.status">
                            <el-option v-for="(item, index) in statusList" :key="index" :label="item.name"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <!--内容-->
        <div class="product-content">
            <div class="table-wrap">
                <div class="common-form">发货单明细</div>

                <el-table :data="orderFrom.deliveryDetailList" border style="width: 100%" min-height="200"
                    v-loading="loading || rowCountLoading" stripe>
                    <el-table-column prop="imagePath" fixed label="商品图片" min-width="150px" align="center">
                        <template #default="scope">
                            <div class="product-info">
                                <div class="info">
                                    <center><img :src="scope.row.imagePath" alt="" style="width:60px;height:60px;border-radius:5px;"></center>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productName" fixed label="商品名称" min-width="200">
                        <template #default="scope">
                            <div class="product-info">
                                <div class="info">
                                    <div class="name">{{ scope.row.productName }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productAttr" label="商品规格" min-width="300">
                        <template #default="scope">

                            <span>{{ scope.row.productAttr }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productSku" label="商品编码" min-width="150" align="center">
                        <template #default="scope">

                            <span>{{ scope.row.productSku }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productAmount" label="商品价格" min-width="90" align="center">
                        <template #default="scope">
                            <el-input-number
                                v-if="orderFrom.status == 20 || orderFrom.status == 30 || orderFrom.status == 40"
                                :min="0" @input="($event) => selCount($event, scope.row, 'productAmount')"
                                v-model="scope.row.productAmount" :controls="false"
                                style="width: 90%"></el-input-number>
                            <div v-else>￥{{ scope.row.productAmount }}</div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="totalNum" label="购买数量" min-width="90" align="center"></el-table-column>
                    <el-table-column prop="totalAmount" label="总价" min-width="130" align="center">
                        <template #default="scope">
                            <div>￥{{ scope.row.totalAmount }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="orderProductType" label="商品类型" width="100" align="center">
                        <template #default="scope">{{ scope.row.orderProductType == 10 ? '销售' :
                            scope.row.orderProductType ==
                                20 ? '赠品' : scope.row.orderProductType == 30 ? '赔付' : '' }}</template>
                    </el-table-column>
                    <el-table-column prop="deliveryNum" label="发货数量" min-width="100" align="center">
                        <template #default="scope">
                            <el-input-number
                                v-if="orderFrom.status == 20 || orderFrom.status == 30 || orderFrom.status == 40"
                                :min="0" @input="($event) => selCount($event, scope.row, 'deliveryNum')"
                                v-model="scope.row.deliveryNum" :controls="false" style="width: 90%"></el-input-number>
                            <span v-else>{{ scope.row.deliveryNum }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="remark" label="备注" width="200"></el-table-column> -->
                    <el-table-column prop="deliveryAmount" label="发货金额" min-width="100" align="center">
                        <template #default="scope">
                            <div>￥{{ scope.row.deliveryAmount }}</div>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- <el-row>
                    <el-col :span="7">
                        <el-form-item label="本次发货总金额">
                            <el-input min="0" v-model="orderFrom.deliveryAmount" placeholder="本次发货总金额" disabled
                                clearable>
                                <template slot="suffix">
                                    <i v-if="rowCountLoading" class="el-icon-loading"></i>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <div class="common-form">付款记录</div>

                <el-table :data="orderFrom.payBill && [orderFrom.payBill]" border style="width: 100%" min-height="200"
                    v-loading="loading" stripe>
                    <el-table-column prop="orderId" min-width="130px" label="订单ID" fixed="left"></el-table-column>
                    <el-table-column prop="billNo" min-width="130px" fixed label="账单号"></el-table-column>
                    <el-table-column prop="payFilePath" fixed width="130" label="支付凭证">
                        <template #default="scope">
                            <img @click="viewImg(scope.row)" v-if="scope.row.payFilePath" :src="scope.row.payFilePath"
                                style="width: 100px;" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="confirmStatus" min-width="100px" label="确认状态">
                        <template #default="scope">
                            {{ scope.row.confirmStatus == 0 ? '未确认' : scope.row.confirmStatus == 1 ? '已确认' : '' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="confirmTime" min-width="150px" label="确认时间"></el-table-column>
                    <el-table-column prop="billAmount" min-width="130px" label="账单金额">
                        <template #default="scope">
                            ￥{{ scope.row.billAmount || '0.00' }}
                        </template>
                    </el-table-column>
                    <!-- DEPOSIT("定金", 1),
AFTER_DEPOSIT("补交定金", 2),
FINAL("尾款", 3); -->
                    <el-table-column prop="billType" min-width="130px" label="类型">
                        <template #default="scope">
                            {{ scope.row.billType == 1 ? '定金' : scope.row.billType == 2 ? '补交定金' : '尾款' }}
                        </template>
                    </el-table-column>

                    <!-- BALANCE("余额支付", 10),
WECHAT("微信支付", 20),
ALIPAY("支付宝支付", 30),
OFFLINE("线下支付",40),
BALANCE_WECHAT("余额微信组合支付",50); -->
                    <el-table-column prop="payType" label="支付方式" min-width="130px">
                        <template #default="scope">
                            {{ scope.row.payType == 10 ? '余额支付' : scope.row.payType == 20 ? '微信支付' : scope.row.payType
                                == 30
                                ? '支付宝支付' : scope.row.payType == 40 ? '线下支付' : scope.row.payType == 50 ? '余额微信组合支付' : ''
                            }}
                        </template>
                    </el-table-column>
                    <!-- PENDING("待付款", 10),
SUCCESS("已付款", 20),
PAYING("支付中",30); -->
                    <el-table-column prop="payStatus" label="支付状态" min-width="130px">
                        <template #default="scope">
                            <el-tag v-if="scope.row.payStatus" :type="scope.row.payStatus == 10 ? 'danger' : ''"> {{
                                scope.row.payStatus == 10 ?
                                    '待付款' : scope.row.payStatus == 20 ? '已付款' : scope.row.payStatus == 30
                                        ? '支付中' : '' }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="payTime" label="支付时间" min-width="150px"></el-table-column>
                    <el-table-column prop="billRemark" label="账单备注" min-width="150px"></el-table-column>
                </el-table>
                <el-divider v-if="orderFrom.auditBtn && orderFrom.status == '10'">审核信息</el-divider>
                <el-form v-if="orderFrom.auditBtn && orderFrom.status == '10'" :model="auditFrom" ref="auditFrom"
                    label-width="150px" class="demo-form-inline">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="审批结果" prop="auditStatus" :rules="[
                                { required: true, message: '审批结果不能为空' }
                            ]">
                                <el-select placeholder="请选择审批结果" v-model="auditFrom.auditStatus">
                                    <el-option v-for="(item, index) in auditList" :key="index" :label="item.name"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="审核意见" prop="auditReason" :rules="[
                                { required: false, message: '审核意见不能为空' }
                            ]">
                                <el-input v-model="auditFrom.auditReason" type="textarea" placeholder="请输入审核意见"
                                    clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div class="dialog-footer" style="display: flex;gap: 10px;margin-top: 5px;">
                    <div style="display: flex;gap:10px;margin-top: 10px;">
                        <div>发货总金额：￥{{ orderFrom.deliveryBeforeAmount || '0.00' }}</div>
                        <div>扣减补位金额：￥{{ orderFrom.depositOutPrice || '0.00' }}</div>
                        <div>本次发货总金额：￥{{ orderFrom.deliveryAmount || '0.00' }}</div>
                    </div>
                    <el-button v-if="orderFrom.auditBtn && orderFrom.status == '10'" type="primary"
                        :loading="auditSaveLoading" @click="auditSave">提交</el-button>
                    <!-- 修改提交 -->
                    <el-button v-auth="'/shipping/btn-edit'" v-if="orderFrom.status == 20" type="primary"
                        :loading="editSaveLoading" @click="editSave">修改保存</el-button>
                </div>
            </div>
        </div>
        <!-- 查看图片 -->
        <el-dialog title="支付凭证" :visible.sync="dialogVisibleImg" width="30%" :before-close="handleClose">
            <img style="margin: 0 auto;" :src="dialogVisibleImgUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
import OrderApi from "@/api/order.js";
import ProductApi from '@/api/product.js';
import { defaultPageSize } from '@/utils/table.js'
export default {
    components: {},
    props: {
        rowData: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            auditFrom: {},
            dialogVisibleImg: false,
            editSaveLoading: false,
            dialogVisibleImgUrl: '',
            auditList: [
                { value: '10', name: '同意' },
                { value: '20', name: '拒绝' },
            ],
            auditSaveLoading: false,
            pageParameter: {},
            orderFrom: {},
            rowCountLoading: false,
            orderProduct: [],
            statusList: [
                {
                    value: 10,
                    name: '审核中'
                },
                {
                    value: 20,
                    name: '待付款'
                },
                {
                    value: 30,
                    name: '付款审批'
                },
                {
                    value: 40,
                    name: '待提货'
                },
                {
                    value: 50,
                    name: '已提货'
                },
                {
                    value: 60,
                    name: '审批拒绝'
                },
            ],
            options: [
                {
                    value: '1',
                    label: '已发货'
                },
                {
                    value: '2',
                    label: '未发货'
                }
            ],
            deliveryTypeList: [
                { name: '门店自提', value: 20 },
            ],
            saveLoading: false,
            /*是否正在加载*/
            loading: false,
            tableData: [],
            /*一页多少条*/
            pageSize: defaultPageSize,
            /*一共多少条数据*/
            totalDataNumber: 0,
            /*当前是第几页*/
            curPage: 1,
            // 是否点击按钮
            isClickRow: false
        };
    },
    created() {
        // const orderDeliveryId = this.$route.query.orderDeliveryId
        console.log(JSON.stringify(this.rowData), 'this.rowData')
        const orderDeliveryId = this.rowData.orderDeliveryId
        this.loadDetail(orderDeliveryId)
    },
    methods: {
        viewImg(row) {
            this.dialogVisibleImgUrl = row.payFilePath
            this.dialogVisibleImg = true;
        },
        auditSave() {
            this.$refs['auditFrom'].validate((valid) => {
                if (valid) {
                    this.auditSaveLoading = true;
                    this.auditFrom['deliveryFlowId'] = this.orderFrom.deliveryFlow.deliveryApplyId
                    ProductApi.deliveryAudit(this.auditFrom, true).then(res => {
                        const { code, data } = res;
                        if (code == 1) {
                            this.auditFromDrawer = false;
                            this.loadDetail(this.rowData.orderDeliveryId)
                            ElMessage({
                                message: '提交成功',
                                type: 'success'
                            });
                        }
                        this.auditSaveLoading = false
                    }).catch(e => {
                        this.auditSaveLoading = false

                    })
                }
            });


        },
        loadDetail(deliveryId) {
            const $this = this
            $this.loading = true
            OrderApi.deliveryDetail({ deliveryId }, true)
                .then(result => {
                    $this.loading = false
                    const { code, data } = result
                    if (code === 1) {
                        console.log('data', data)
                        this.orderFrom = data;
                    }
                }).catch(error => {
                    $this.loading = false
                })
        },
        closeDialog() {
            this.$emit('closeDialog')
        },
        addSave() {
            // 暂时取消
            if (this.orderProduct.some(val => !val.deliveryCount)) {
                return ElMessage.warning("请完善表格数据在提交!");
            }
            let obj = {
                orderId: this.orderFrom.orderId,
                deliveryNo: this.orderFrom.deliveryNo,
                deliveryTotalAmount: this.orderFrom.deliveryTotalAmount,
                productList: this.orderProduct
            }
            console.log(obj, 'obj')
            this.saveLoading = true;
            ProductApi.deliveryV2(obj).then(res => {
                const { code, data } = res;
                this.saveLoading = false;
                if (code == 1) {
                    ElMessage({
                        message: '提交成功',
                        type: 'success'
                    });
                    this.$emit('addSave')
                    this.closeDialog();
                }
            })
        },
        filterTypeName(value) {
            const item = this.productTypes.find(f => f.value === value)
            if (item)
                return item.name
            return ''
        },
        /*每页多少条*/
        handleSizeChange(val) {
            this.pageSize = val;
            this.getData();
        },
        /*选择第几页*/
        handleCurrentChange(val) {
            let self = this;
            self.loading = true;
            self.curPage = val;
            self.getData();
        },
        // 前端随机生成id
        getRandomLetter() {
            const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            return letters.charAt(Math.floor(Math.random() * letters.length));
        },
        // 修改提交
        editSave() {
            this.editSaveLoading = true;
            let Arr = []
            this.orderFrom.deliveryDetailList.map(val => {
                let obj = {}
                obj['deliveryDetailId'] = val.deliveryDetailId
                obj['productAmount'] = val.productAmount
                obj['deliveryNum'] = val.deliveryNum
                Arr.push(obj)
            })
            let obj = {
                "orderDeliveryId": this.orderFrom.orderDeliveryId,
                deliveryBeforeAmount: this.orderFrom.deliveryBeforeAmount,
                deliveryTotalAmount: this.orderFrom.deliveryTotalAmount,
                // deliveryTotalNum: '',
                depositOutPrice: this.orderFrom.depositOutPrice,
                "deliveryDetailList": Arr
            }
            ProductApi.deliveryUpdate(obj, true).then(res => {
                const { code, data } = res;
                this.editSaveLoading = false;
                if (code == 1) {
                    ElMessage({
                        message: '提交成功',
                        type: 'success'
                    });
                    this.closeDialog();
                }
            })
        },
        // 修改数量计算金额
        selCount(e, row, type) {
            console.log(e, type)
            // if (row.deliveryCount) {
            this.rowCountLoading = true;
            let obj = {}
            if (row.orderProductId) {
                obj = { productPrice: type == 'productAmount' ? e : row.productAmount, orderProductId: row.orderProductId, productSkuId: row.productSkuId, orderProductType: row.orderProductType, deliveryNum: type == 'deliveryNum' ? e || 0 : row.deliveryNum || 0, specType: row.sendType || row.specType }
            }
            ProductApi.deliveryCalc(obj, true).then(res => {
                console.log(res, 'res')
                const { code, data } = res;
                row['deliveryAmount'] = data;
                // 计算总金额
                let Count = 0;
                this.orderFrom.deliveryDetailList.map(val => {
                    Count += Number(val.deliveryAmount || '0');
                })
                this.orderFrom.deliveryBeforeAmount = Number(Count).toFixed(2)
                // this.orderFrom.deliveryAmount = Count - Number(this.orderFrom.depositOutAmount || 0);
                // deliveryAmount 本次发货金额
                // depositOutAmount 定金补位
                // 如果列表的发货金额累加 大于定金补位(下单生成的)
                if (Count >= Number(this.orderFrom.depositOutAmount)) {
                    // 本次发货总金额(按钮左边的数字) = 列表的发货金额累加 - 定金补位(下单生成的)
                    this.orderFrom.deliveryAmount = (Count - Number(this.orderFrom.depositOutAmount || 0)).toFixed(2);
                    // 本次补位余额 还是等于 定金补位(下单生成的)
                    this.orderFrom.depositOutPrice = this.orderFrom.depositOutAmount;
                } else {
                    // 否则如果 定金补位(下单生成的) 大于 列表的发货金额累加
                    // 本次补位余额 等于 列表的发货金额累加 - 定金补位(下单生成的)
                    this.orderFrom.depositOutPrice = Count;
                    // 本次发货总金额(按钮左边的数字) = 0
                    this.orderFrom.deliveryAmount = 0;
                }
                console.log(this.orderFrom.depositOutAmount, 'this.orderFrom.depositOutAmount')
                console.log(this.orderFrom.deliveryAmount, 'this.orderFrom.deliveryAmount')

                this.orderFrom = JSON.parse(JSON.stringify(this.orderFrom))
                this.rowCountLoading = false;
            }).catch(e => {
                this.rowCountLoading = false;
            })
            // }

        },
        generateRandomLetterArray(length = 10) {
            const randomLetterArray = [];
            for (let i = 0; i < length; i++) {
                randomLetterArray.push(this.getRandomLetter());
            }
            return randomLetterArray.join("");
        },
        /*获取列表*/
        getData() {
            let self = this;
            this.loading = true;
            let Params = {
                orderId: this.rowData.orderId
            }
            ProductApi.toDelivery(Params, true)
                .then(res => {
                    console.log(res, 'res')
                    this.loading = false
                    const { code, data } = res;
                    if (code == 1) {
                        const { order, orderProduct, deliveryNo, deliveryTime, deliveryType, deliveryUserName, deliveryUserId } = data;
                        this.orderFrom = { ...order, deliveryNo, deliveryTime, deliveryType, deliveryUserName, deliveryUserId };
                        this.orderProduct = orderProduct;
                        this.orderProduct.map(val => {
                            val['rowID'] = this.generateRandomLetterArray();
                        })
                        console.log(this.orderProduct, 'this.orderProduct')
                    }

                })
                .catch(error => {
                    self.loading = false;
                });
        },
        tagClick(row, cor) {
            row.colorList.map(val => val.check = false)
            cor.check = !cor.check;
            if (cor.check) {
                row.productSkuId = cor.productSkuId
                row.productAttr = cor.productAttr
            }
        },
        // 前端删除
        delRow(row) {
            const set1 = new Set([row].map(item => item['rowID']))
            const set2 = new Set(this.orderProduct.map(item => item['rowID']))
            const diff = [
                ...[row].filter(item => !set2.has(item['rowID'])),
                ...this.orderProduct.filter(item => !set1.has(item['rowID']))
            ]
            this.orderProduct = diff;
        },
        // 超量超规格发货
        async copyRow(row, type) {
            // sendType "正常发货" type:20 "超量发货" type:30 "超规格发货" type:40
            this.isClickRow = true
            let _row = JSON.parse(JSON.stringify(row))
            _row['rowID'] = this.generateRandomLetterArray();
            _row['sendType'] = type;
            // 超规格
            if (type == '40') {
                await this.skuList(_row, row.productId);
            }
            this.orderProduct.push(_row);

        },
        // 获取规格
        skuList(_row, productId) {
            ProductApi.skuList({ productId }).then(res => {
                const { code, data } = res;
                console.log(data, 'data-----')
                _row['colorList'] = data
                //默认选择第一个
                _row['colorList'][0]['check'] = true;
                _row['productSkuId'] = data[0]['productSkuId']
                this.orderProduct = JSON.parse(JSON.stringify(this.orderProduct))

            })
        },
    }
};
</script>

<style scoped>
/deep/.el-tag {
    cursor: pointer !important;
    margin: 0 4px !important;
}
</style>